package com.design.util;

import com.design.command.NetCommand;

import java.io.*;
import java.util.ArrayList;

/**
 * @author leali
 * @title: FileUtil
 * @projectName design
 * @description: 文件处理器
 * @date 2022/1/3 17:42
 */
public class FileUtil {
    public static final String FILE_NAME = "res/config.log";

    /**
     * 将命令集合写入日志文件
     *
     * @param commands command list
     */
    public static void writeCommands(ArrayList<NetCommand> commands) {
        try {
            FileOutputStream file = new FileOutputStream(FILE_NAME);
            //创建对象输出流用于将对象写入到文件中
            ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(file));
            //将对象写入文件
            outputStream.writeObject(commands);
            outputStream.close();
        } catch (Exception e) {
            System.out.println("命令保存失败！");
            e.printStackTrace();
        }
    }

    /**
     * 从日志文件中提取命令集合
     *
     * @return ArrayList<Command>
     */
    public static ArrayList<NetCommand> readCommands() {
        try {
            FileInputStream file = new FileInputStream(FILE_NAME);
            //创建对象输入流用于从文件中读取对象
            ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(file));

            //将文件中的对象读出并转换为ArrayList类型
            ArrayList<NetCommand> commands = (ArrayList<NetCommand>) inputStream.readObject();
            inputStream.close();
            return commands;
        } catch (Exception e) {
            System.out.println("命令读取失败！");
            e.printStackTrace();
            return null;
        }
    }
}
